#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Charles.chen
# createDate:2017/9/5
# Title:
# Tip:
import time
import datetime
import json
import os
from collections import Iterable
from app.toolkit.configSingle import ConfigSingle
import hashlib

# 今天日期
today = datetime.date.today()
# 昨天时间
yesterday = today - datetime.timedelta(days=1)


# 将peewee查询对象转化为dict
def convertDbObjToDict(objs, cls):
    dict_array = []
    fields = getFieldsFromModelCls(cls)
    if not isinstance(objs, Iterable):
        dict_item = {}
        for i in fields:
            if getattr(objs, i) is not None:
                dict_item.setdefault(i, getattr(objs, i))
            pass
        return dict_item
    for obj in objs:
        dict_item = {}
        for i in fields:
            if getattr(obj, i) is not None:
                dict_item.setdefault(i, getattr(obj, i))
            pass
        dict_array.append(dict_item)
        pass
    return dict_array

# 从peewee model类中获得声明属性
def getFieldsFromModelCls(cls):
    declared_fields = []
    for k, v in dict(cls.__dict__).items():
        if hasattr(v, "field"):
            declared_fields.append(k)
        pass
    return declared_fields


# 生成返回obj->成功
def buildSucc(data):
    res = {
        "status": 1,
        "data": data
    }
    return json.dumps(res)

# 生成返回obj->失败
def buildErr(msg):
    res = {
        "status": 0,
        "data": msg
    }
    return json.dumps(res)

# 生成返回obj->无返回结果
def buildNone():
    res = {
        "status": 2,
        "data": None
    }
    return json.dumps(res)

# 获取当前时间 str
def getNowStr():
    return str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

# 获取当前时间 date
def getNowDate():
    return datetime.datetime.now()

# 获取当前时间 str 自定义时间格式
def getNowFormat(fm="%Y-%m-%d %H:%M:%S"):
    return str(datetime.datetime.now().strftime(fm).format(fm=fm))

# 返回当前时间的时间戳
def getNowUnix():
    return time.time()

# 获取昨天的开始时间时间戳(00:00)
def getLastDayUnixBegin():
    return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))

# 获取昨天的结束时间时间戳(23:59)
def getLastDayUnixEnd():
    return int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) - 1

# 根据域名和接口 拼装一个完整的http请求网址
def buildHttpRequestUrl(domain_address, domain_inerface):
    return "/".join(["http:/", domain_address, domain_inerface])

# 获取时间
def getDateTimeOver():
    pass

# 获取时间
def getTimeOver():
    pass

# 复制文件A到指定文件B
# open(targetFile, "wb").write(open(sourceFile, "rb").read())
def copyFileToTarget(sourceFile=None, targetFile=None):
    sFile = open(sourceFile, "rb")
    tFile = open(targetFile, "wb")
    tFile.write(sFile.read())
    tFile.close()
    sFile.close()
    pass

# 获取指定目录下的所有文件 除py后缀
# [{"name":"xxx", "size":23}]
# default []
def getIotXConfigList(path=None):
    if path is None:
        return []
    fileNames = []
    files = os.listdir(path)
    for fl in files:
        if not os.path.isdir(fl):
            fNameArr = fl.split(".")
            if fNameArr[1] != 'py':
                flpath = "/".join([path, fl])
                # 单位 KB
                fileInfo = {
                    "size": round(os.path.getsize(flpath) / 1024, 2),
                    "name": fNameArr[0].decode("gbk").encode("utf-8")
                }
                fileNames.append(fileInfo)
            pass
    return fileNames

# 获取项目的安全性签名
# return now(unix) md5(pwd)
def getProjectSign():
    unixTime = getNowUnix()
    m = hashlib.md5()
    configObj = ConfigSingle()
    iotId = configObj.configuration.get("system_conf", "unique_id")
    signStr = "_".join([str(iotId), "anosi", "hehe", str(unixTime)])
    m.update(signStr)
    return unixTime, m.hexdigest()


